import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, SafeAreaView, TextInput, TouchableOpacity, Image, Modal, FlatList, ActivityIndicator, RefreshControl, Dimensions } from 'react-native';
import Header from '../../../components/Header';
import { getIPQCHeaderLis } from './api';
import CustomQRScanner from '../../../components/CustomQRScanner';
import saoma from '../../../assets/saoma.png';

interface IpqcProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
    onNavigateToScreen?: (route: string) => void;
}

const tabs = [
    { id: 1, label: '待质检', state: 1 },
    { id: 2, label: '质检中', state: 2 },
    { id: 3, label: '已质检', state: 3 },
];

const Ipqc: React.FC<IpqcProps> = ({ onNavigateToLogin, onBackPress, onNavigateToScreen }) => {
    const [search, setSearch] = useState('');
    const [scanVisible, setScanVisible] = useState(false);
    const [activeTab, setActiveTab] = useState(1);
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<any>(null);
    const [refreshing, setRefreshing] = useState(false);
    const [current, setCurrent] = useState(1);
    const [size] = useState(10);
    const [hasMore, setHasMore] = useState(true);
    const [loadingMore, setLoadingMore] = useState(false);
    const [imageModalVisible, setImageModalVisible] = useState(false);
    const [selectedImage, setSelectedImage] = useState<string>('');

    useEffect(() => {
        fetchData('', activeTab, false);
    }, [activeTab]);

    const fetchData = async (keyword: string, stateValue: number, isLoadMore: boolean) => {
        if (isLoadMore) {
            setLoadingMore(true);
        } else {
            setLoading(true);
            setCurrent(1);
            setHasMore(true);
        }
        try {
            const params: any = {
                current: isLoadMore ? current + 1 : 1,
                size,
                state: stateValue,
                check_type: 1,
            };
            if (keyword) params.keyword = keyword;
            const response = await getIPQCHeaderLis(params);
            const newRecords = response?.data?.records || [];
            const total = response?.data?.total || 0;
            if (isLoadMore) {
                setData((prev: any) => ({
                    ...prev,
                    records: [...(prev?.records || []), ...newRecords],
                    current: response.data.current,
                    total: response.data.total,
                    pages: response.data.pages
                }));
                setCurrent((prev: number) => prev + 1);
            } else {
                setData(response.data);
                setCurrent(1);
            }
            const totalLoaded = isLoadMore ? (data?.records?.length || 0) + newRecords.length : newRecords.length;
            setHasMore(totalLoaded < total);
        } catch (error) {
            if (!isLoadMore) setData(null);
        } finally {
            if (isLoadMore) setLoadingMore(false);
            else setLoading(false);
        }
    };

    const handleSearchChange = (text: string) => {
        setSearch(text);
        clearTimeout((global as any).searchTimeout);
        (global as any).searchTimeout = setTimeout(() => {
            fetchData(text, activeTab, false);
        }, 500);
    };

    const onScanPress = () => {
        setScanVisible(true);
    };

    const onBarcodeScan = (data: string) => {
        setScanVisible(false);
        setSearch(data);
        fetchData(data, activeTab, false);
    };

    const handleTabPress = (tabId: number) => {
        setActiveTab(tabId);
    };

    const handleRefresh = async () => {
        setRefreshing(true);
        await fetchData(search, activeTab, false);
        setRefreshing(false);
    };

    const handleLoadMore = () => {
        if (hasMore && !loadingMore && !loading) {
            fetchData(search, activeTab, true);
        }
    };

    const renderItem = ({ item }: { item: any }) => (
        <TouchableOpacity
            style={styles.card}
            onPress={() => {
                if (item.state === 3) return; // 已质检不跳转
                if (onNavigateToScreen) {
                    // 将ipqc_num传递给详情页面
                    (global as any).ipqcDetailData = { ipqc_num: item.ipqc_num };
                    onNavigateToScreen('Quality/Ipqc/IpqcDetail');
                }
            }}
            activeOpacity={item.state === 3 ? 1 : 0.8}
        >
            <View style={styles.cardHeader}>
                <TouchableOpacity
                    style={styles.imageContainer}
                    onPress={() => {
                        setSelectedImage(item.product_link ? String(item.product_link) : '');
                        setImageModalVisible(true);
                    }}
                >
                    <Image
                        source={item.product_link ? { uri: String(item.product_link) } : require('../../../assets/zwtp.png')}
                        style={styles.productImage}
                        resizeMode="contain"
                    />
                </TouchableOpacity>
                <View style={styles.headerInfo}>
                    <Text style={styles.inspectionNumber}>检验单号</Text>
                    <Text style={styles.inspectionNumberValue}>{item.ipqc_num}</Text>
                    <Text style={styles.workOrderNumber}>订单号</Text>
                    <Text style={styles.workOrderNumberValue}>{item.odd_num || '无'}</Text>
                </View>
            </View>
            <View style={styles.section}>
                <View style={styles.infoRow}>
                    <Text style={styles.infoLabel}>物料编码</Text>
                    <Text style={styles.infoValue}>{item.product_encode}</Text>
                </View>
                <View style={styles.infoRow}>
                    <Text style={styles.infoLabel}>物料名称</Text>
                    <Text style={styles.infoValue}>{item.product_name}</Text>
                </View>
                <View style={styles.infoRow}>
                    <Text style={styles.infoLabel}>物料规格</Text>
                    <Text style={styles.infoValue}>{item.product_specs}</Text>
                </View>
            </View>
            <View style={styles.section}>
                <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
                    <View style={{ flex: 1, alignItems: 'center' }}>
                        <Text style={styles.infoLabelCenter}>供应商</Text>
                        <Text style={styles.infoValueCenter}>{item.supplier_name}</Text>
                    </View>
                    <View style={{ flex: 1, alignItems: 'center' }}>
                        <Text style={styles.infoLabelCenter}>批次号</Text>
                        <Text style={styles.infoValueCenter}>{item.batch_num || '无'}</Text>
                    </View>
                    <View style={{ flex: 1, alignItems: 'center' }}>
                        <Text style={styles.infoLabelCenter}>数量</Text>
                        <Text style={styles.infoValueCenter}>{item.quantity}</Text>
                    </View>
                </View>
            </View>
            {/* 第三部分：报检时间（已质检时显示检验时间，两行） */}
            <View style={styles.section}>
                <View style={styles.infoRow}>
                    <Text style={styles.infoLabel}>报检时间</Text>
                    <Text style={styles.infoValue}>{item.create_time}</Text>
                </View>
                {item.state === 3 && (
                    <View style={styles.infoRow}>
                        <Text style={styles.infoLabel}>检验时间</Text>
                        <Text style={styles.infoValue}>{item.qc_time || '--'}</Text>
                    </View>
                )}
            </View>
        </TouchableOpacity>
    );

    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="过程检"
                showBackButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
            />
            {/* 顶部搜索和扫码区 */}
            <View style={styles.topBar}>
                <View style={styles.inputContainer}>
                    <TextInput
                        style={styles.searchInput}
                        placeholder="请输入检验单号搜索"
                        placeholderTextColor="#999"
                        value={search}
                        onChangeText={handleSearchChange}
                    />
                    {search.length > 0 && (
                        <TouchableOpacity
                            style={styles.clearButton}
                            onPress={() => {
                                setSearch('');
                                fetchData('', activeTab, false);
                            }}
                        >
                            <Text style={styles.clearButtonText}>×</Text>
                        </TouchableOpacity>
                    )}
                </View>
                <TouchableOpacity style={styles.scanBtn} onPress={onScanPress}>
                    <Image source={saoma} style={{ width: 30, height: 30 }} />
                </TouchableOpacity>
            </View>
            {/* 扫码模态框 */}
            <Modal visible={scanVisible} animationType="slide">
                <CustomQRScanner
                    onRead={onBarcodeScan}
                    onClose={() => setScanVisible(false)}
                />
            </Modal>
            {/* 标签页 */}
            <View style={styles.tabContainer}>
                {tabs.map((tab) => (
                    <TouchableOpacity
                        key={tab.id}
                        style={[
                            styles.tabItem,
                            activeTab === tab.id && styles.tabItemActive
                        ]}
                        onPress={() => handleTabPress(tab.id)}
                    >
                        <Text style={[
                            styles.tabText,
                            activeTab === tab.id && styles.tabTextActive
                        ]}>
                            {tab.label}
                        </Text>
                        {activeTab === tab.id && <View style={styles.tabIndicator} />}
                    </TouchableOpacity>
                ))}
            </View>
            {/* 列表内容 */}
            {loading ? (
                <View style={styles.loadingContainer}>
                    <ActivityIndicator size="large" color="#0076ff" />
                    <Text style={styles.loadingText}>加载中...</Text>
                </View>
            ) : (
                <FlatList
                    data={data?.records || []}
                    keyExtractor={(item) => item.id}
                    renderItem={renderItem}
                    contentContainerStyle={styles.listContainer}
                    onEndReached={handleLoadMore}
                    onEndReachedThreshold={0.1}
                    refreshControl={
                        <RefreshControl
                            refreshing={refreshing}
                            onRefresh={handleRefresh}
                            colors={['#0076ff']}
                            tintColor="#0076ff"
                        />
                    }
                    ListEmptyComponent={
                        <View style={styles.emptyContainer}>
                            <Image
                                source={require('../../../assets/zwsj.png')}
                                style={styles.emptyImage}
                                resizeMode="contain"
                            />
                            <Text style={styles.emptyText}>暂无数据</Text>
                        </View>
                    }
                    ListFooterComponent={
                        loadingMore ? (
                            <View style={styles.loadingMoreContainer}>
                                <ActivityIndicator size="small" color="#0076ff" />
                                <Text style={styles.loadingMoreText}>加载更多...</Text>
                            </View>
                        ) : null
                    }
                />
            )}
            {/* 图片全屏显示模态框 */}
            <Modal visible={imageModalVisible} transparent={true} animationType="fade">
                <View style={styles.imageModalContainer}>
                    <TouchableOpacity
                        style={styles.imageModalOverlay}
                        onPress={() => setImageModalVisible(false)}
                    >
                        <Image
                            source={selectedImage ? { uri: selectedImage } : require('../../../assets/zwtp.png')}
                            style={styles.fullScreenImage}
                            resizeMode="contain"
                        />
                    </TouchableOpacity>
                </View>
            </Modal>
        </SafeAreaView>
    );
};

const { width } = Dimensions.get('window');

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    topBar: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 10,
        paddingTop: 10,
        paddingBottom: 10,
    },
    inputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
        position: 'relative',
    },
    searchInput: {
        flex: 1,
        height: 40,
        backgroundColor: '#fff',
        borderRadius: 17,
        paddingHorizontal: 16,
        paddingRight: 40,
        paddingVertical: 8,
        fontSize: 15,
        marginRight: 10,
    },
    clearButton: {
        position: 'absolute',
        right: 10,
        top: 0,
        bottom: 0,
        justifyContent: 'center',
        alignItems: 'center',
        width: 30,
        height: 30,
    },
    clearButtonText: {
        color: '#999',
        fontSize: 16,
        fontWeight: 'bold',
        textAlign: 'center',
        textAlignVertical: 'center',
        lineHeight: 40,
        includeFontPadding: false,
        paddingTop: 0,
        paddingBottom: 0,
    },
    scanBtn: {
        width: 40,
        height: 40,
        borderRadius: 20,
        backgroundColor: '#fff',
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: '#eee',
    },
    tabContainer: {
        flexDirection: 'row',
        backgroundColor: '#fff',
        paddingHorizontal: 10,
        paddingBottom: 10,
    },
    tabItem: {
        flex: 1,
        alignItems: 'center',
        paddingVertical: 12,
        position: 'relative',
    },
    tabItemActive: {},
    tabText: {
        fontSize: 16,
        color: '#666',
        fontWeight: '500',
    },
    tabTextActive: {
        color: '#0076ff',
        fontWeight: 'bold',
    },
    tabIndicator: {
        position: 'absolute',
        bottom: 0,
        left: '50%',
        marginLeft: -15,
        width: 30,
        height: 3,
        backgroundColor: '#0076ff',
        borderRadius: 2,
    },
    listContainer: {
        padding: 10,
    },
    card: {
        backgroundColor: '#fff',
        borderRadius: 8,
        marginBottom: 12,
        padding: 15,
        shadowColor: '#000',
        shadowOpacity: 0.1,
        shadowRadius: 4,
        shadowOffset: { width: 0, height: 2 },
        elevation: 3,
    },
    cardHeader: {
        flexDirection: 'row',
        marginBottom: 12,
    },
    productImage: {
        width: 60,
        height: 60,
        borderRadius: 6,
        backgroundColor: '#f0f0f0',
        marginRight: 12,
    },
    headerInfo: {
        flex: 1,
    },
    inspectionNumber: {
        fontSize: 12,
        color: '#666',
        marginBottom: 2,
    },
    inspectionNumberValue: {
        fontSize: 12,
        color: '#333',
        marginBottom: 2,
    },
    workOrderNumber: {
        fontSize: 12,
        color: '#666',
        marginBottom: 2,
    },
    workOrderNumberValue: {
        fontSize: 12,
        color: '#333',
    },
    section: {
        backgroundColor: '#f8f9fa',
        borderRadius: 6,
        padding: 12,
        marginBottom: 8,
    },
    infoRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: 6,
    },
    infoLabel: {
        fontSize: 14,
        color: '#666',
        minWidth: 70,
        textAlign: 'left', // 恢复为左对齐
    },
    infoValue: {
        fontSize: 14,
        color: '#333',
        flex: 1,
        textAlign: 'right', // 恢复为右对齐
    },
    loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 50,
    },
    loadingText: {
        marginTop: 10,
        fontSize: 16,
        color: '#666',
    },
    emptyContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 50,
    },
    emptyImage: {
        width: 200,
        height: 200,
        marginBottom: 16,
    },
    emptyText: {
        fontSize: 16,
        color: '#999',
    },
    loadingMoreContainer: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: 15,
    },
    loadingMoreText: {
        marginLeft: 8,
        fontSize: 14,
        color: '#666',
    },
    infoLabelCenter: {
        fontSize: 14,
        color: '#666',
        textAlign: 'center',
    },
    infoValueCenter: {
        fontSize: 14,
        color: '#333',
        textAlign: 'center',
    },
    imageContainer: {
        position: 'relative',
        zIndex: 10,
    },
    imageModalContainer: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.9)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    imageModalOverlay: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        width: '100%',
        height: '100%',
    },
    fullScreenImage: {
        width: width,
        height: width,
    },
});

export default Ipqc; 